﻿using System.Collections;
using System.Collections.Generic;
using UFrame.PD;
using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 读取AB包的方式
    /// </summary>
    public sealed class GameConfig : MaMono<GameConfig>
    {
        private GameConfig()
        {
        }

        public ELoadType loadType = ELoadType.Editor;


        protected void Awake()
        {
            base.Awake();
            ResourcesMa.loadType = loadType;
            isInit = true;
        }

        public void LoadAB(string[] abNameAry)
        {
            StartCoroutine(CorLoadAB(abNameAry));
        }

        private IEnumerator CorLoadAB(string[] abNameAry)
        {
            List<AssetBundle> abList = new List<AssetBundle>();

            foreach (var abName in abNameAry)
            {
                var aq = ResourcesMa.LoadABAsync(abName);
                yield return aq;
                abList.Add(aq.assetBundle);
            }

            foreach (var ab in abList)
            {
                if (ab == null)
                {
                    continue;
                }

                string[] assetNames = ab.GetAllAssetNames();
                List<AssetBundleRequest> aqList = new List<AssetBundleRequest>();
                foreach (var item in assetNames)
                {
                    AssetBundleRequest aq = ab.LoadAssetAsync(item);
                    aqList.Add(aq);
                }

                #region 测试代码

                // TODO test if
                //if (ab.isStreamedSceneAssetBundle)
                //{
                //    PLDebug.Log("场景AB包");
                //    string[] aryList = ab.GetAllAssetNames();
                //    foreach (var name in aryList)
                //    {
                //        PLDebug.Log("场景 " + name);
                //    }
                //}
                //end

                //List<AssetBundleRequest> newList = new List<AssetBundleRequest>();

                #endregion


                for (int i = 0; i < aqList.Count; i++)
                {
                    while (aqList[i].isDone == false)
                    {
                        if (aqList[i].isDone)
                        {
                            break;
                        }

                        yield return new WaitForFixedUpdate();
                    }

                    ResourcesMa.AddObject(ab.name, assetNames[i], aqList[i].asset);
                }
            }

            foreach (var item in abList)
            {
                item.Unload(false);
            }

            EventMa.Notify(ABLoadCompleteArgs.EventId);
        }
    }
}